using B.S.XZYData.Api.Wrter.Application.Command.AssemblyWorkOrder;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System.Transactions;
using System.Linq;

namespace B.S.XZYData.Api.Wrter.Application.Handler.AssemblyWorkOrder
{
    /// <summary>
    /// 批量删除装配工单处理器
    /// </summary>
    public class BatchDeleteAssemblyWorkOrderHandler : IRequestHandler<BatchDeleteAssemblyWorkOrderCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Domain.ZSHH.AssemblyWorkOrder> _assemblyWorkOrderRepo;
        private readonly IBaseRepository<AssemblyWorkOrderProductDetail> _productDetailRepo;
        private readonly ILogger<BatchDeleteAssemblyWorkOrderHandler> _logger;

        public BatchDeleteAssemblyWorkOrderHandler(
            IBaseRepository<Domain.ZSHH.AssemblyWorkOrder> assemblyWorkOrderRepo,
            IBaseRepository<AssemblyWorkOrderProductDetail> productDetailRepo,
            ILogger<BatchDeleteAssemblyWorkOrderHandler> logger)
        {
            _assemblyWorkOrderRepo = assemblyWorkOrderRepo;
            _productDetailRepo = productDetailRepo;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(BatchDeleteAssemblyWorkOrderCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();
            try
            {
                if (request.Ids == null || !request.Ids.Any())
                {
                    res.Msg = "请选择要删除的装配工单";
                    res.Code = ApiEnum.Fail;
                    return await System.Threading.Tasks.Task.FromResult(res);
                }

                var successCount = 0;
                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    foreach (var id in request.Ids)
                    {
                        try
                        {
                            // 验证装配工单是否存在
                            var existingWorkOrder = await _assemblyWorkOrderRepo.GetValue(id);
                            if (existingWorkOrder == null || existingWorkOrder.IsDeleted)
                            {
                                continue;
                            }

                            // 逻辑删除装配工单
                            existingWorkOrder.IsDeleted = true;
                            existingWorkOrder.Updator = request.Deleter;
                            existingWorkOrder.UpdatorDate = DateTime.Now;

                            var workOrderResult = await _assemblyWorkOrderRepo.UpdateAsync(existingWorkOrder);
                            if (workOrderResult > 0)
                            {
                                // 逻辑删除关联的产品明细
                                var existingProductDetails = _productDetailRepo.GetAll()
                                    .Where(x => !x.IsDeleted && x.WorkOrderId == id)
                                    .ToList();

                                if (existingProductDetails.Any())
                                {
                                    foreach (var detail in existingProductDetails)
                                    {
                                        detail.IsDeleted = true;
                                        detail.Updator = request.Deleter;
                                        detail.UpdatorDate = DateTime.Now;
                                        await _productDetailRepo.UpdateAsync(detail);
                                    }
                                }

                                successCount++;
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError($"删除装配工单ID {id} 时发生异常：{ex.Message}");
                            // 继续处理其他ID，不中断整个批量操作
                        }
                    }

                    scope.Complete();
                    res.Data = successCount;
                    res.Code = ApiEnum.Success;
                    res.Msg = $"批量删除成功，共删除 {successCount} 条装配工单";
                }

                return await System.Threading.Tasks.Task.FromResult(res);
            }
            catch (Exception ex)
            {
                _logger.LogError($"批量删除装配工单异常：{ex.Message}");
                res.Msg = "批量删除装配工单异常：" + ex.Message;
                res.Code = ApiEnum.Error;
                return await System.Threading.Tasks.Task.FromResult(res);
            }
        }
    }
} 